package com.zengde.ai_sandbox.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class ChatSessionManager {
    
    private final SuperBigModelInterface bigModel;
    private final Map<String, String> customerServicePairings;
    private final Map<String, Integer> serviceLoadCount;
    
    @Value("${chat.max-customers-per-service}")
    private int maxCustomersPerService;
    
    public ChatSessionManager(SuperBigModelInterface bigModel) {
        this.bigModel = bigModel;
        this.customerServicePairings = new ConcurrentHashMap<>();
        this.serviceLoadCount = new ConcurrentHashMap<>();
    }
    
    /**
     * 客户发起聊天请求
     * @param customerId 客户ID
     * @param content 聊天内容
     * @return 是否成功配对客服
     */
    public boolean initiateChat(String customerId, String content) {
        // 如果客户已经在聊天中，直接返回true
        if (customerServicePairings.containsKey(customerId)) {
            return true;
        }
        
        // 查找负载最小的客服
        String serviceId = findLeastLoadedService();
        if (serviceId == null) {
            return false; // 所有客服都已满载
        }
        
        // 建立配对
        customerServicePairings.put(customerId, serviceId);
        serviceLoadCount.merge(serviceId, 1, Integer::sum);
        
        // 初始化会话
        String sessionId = generateSessionId(customerId, serviceId);
        String rolePrompt = generateRolePrompt(customerId);
        bigModel.initializeSession(sessionId, rolePrompt);
        
        return true;
    }
    
    /**
     * 发送消息
     * @param customerId 客户ID
     * @param content 消息内容
     * @return 模型响应
     */
    public String sendMessage(String customerId, String content) {
        String serviceId = customerServicePairings.get(customerId);
        if (serviceId == null) {
            throw new IllegalStateException("Customer not in active chat");
        }
        
        String sessionId = generateSessionId(customerId, serviceId);
        return bigModel.ntns(sessionId, content);
    }
    
    /**
     * 发送流式消息
     * @param customerId 客户ID
     * @param content 消息内容
     * @return 模型流式响应
     */
    public Flux<String> sendStreamMessage(String customerId, String content) {
        String serviceId = customerServicePairings.get(customerId);
        if (serviceId == null) {
            return Flux.error(new IllegalStateException("Customer not in active chat"));
        }
        
        String sessionId = generateSessionId(customerId, serviceId);
        return bigModel.nts(sessionId, content);
    }
    
    /**
     * 结束聊天
     * @param customerId 客户ID
     */
    public void endChat(String customerId) {
        String serviceId = customerServicePairings.remove(customerId);
        if (serviceId != null) {
            serviceLoadCount.merge(serviceId, -1, Integer::sum);
        }
    }
    
    private String findLeastLoadedService() {
        return serviceLoadCount.entrySet().stream()
                .filter(e -> e.getValue() < maxCustomersPerService)
                .min(Map.Entry.comparingByValue())
                .map(Map.Entry::getKey)
                .orElse(null);
    }
    
    private String generateSessionId(String customerId, String serviceId) {
        return serviceId + "_" + customerId;
    }
    
    private String generateRolePrompt(String customerId) {
        return String.format("""
                你是一个专业的客服人员，正在和客户 %s 对话。
                请以专业、友好的态度回答客户的问题。
                记住要简明扼要，一次回答不要超过100字。
                如果遇到无法回答的问题，请礼貌地表示会转接给人工客服。
                """, customerId);
    }
}
